package com.mytrip.util.reqcache;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

/**
 * @project backend
 * 
 * @author <a href="mailto:yuanchongyu1@163.com">yuanchongyu</a>
 * 
 * @createDate Aug 20, 2010 3:21:49 PM
 * 
 */
public class ReqCacheUtil{
	private static final Log log = LogFactory.getLog(ReqCacheUtil.class);

	public static final String GET_PRODUCTMERCHANT_BY_ID = "$__rc_getProductMerchantById";

	public static final String GET_PRODUCTMERCHANT = "$__rc_getProductMerchant";

	public static final String GET_PRODUCTMERCHANT_BY_PRODUCTID = "$__rc_getProductMerchantByProductId";

	public static final String GET_PRODUCT_BY_ID = "$__rc_getProductById";

	public static final String GET_PRODUCTSUPPLIER = "$__rc_getProductSupplier";
	
	public static final String GET_PRODUCTSUPPLIER_BY_ID = "$__rc_getProductSupplierById";

	public static final String GET_LISTCURPRODUCTCATEGTREE = "$__rc_listCurProductCategTree";

	public static final String REQ_CACHE_SPLIT = "_";

	private static HttpServletRequest getRequest(){
		HttpServletRequest request = ServletActionContext.getRequest();
		if (request == null) {
			WebContext webContext = WebContextFactory.get();
			if (webContext != null) {
				request = webContext.getHttpServletRequest();
			}
		}
		if (request == null) {
			log.info("can't find HttpServletRequest in any scope.");
		}
		return request;
	}

	public static Object get(String attrKey, String mapKey){
		Object res = null;
		HttpServletRequest req = getRequest();
		if (req != null) {
			Map<String, Object> map = (Map<String, Object>) req.getAttribute(attrKey);
			if (map != null) {
				res = map.get(mapKey);
			}
		}
		return res;
	}

	public static void put(String attrKey, String mapKey, Object mapValue){
		HttpServletRequest req = getRequest();
		if (req == null || mapKey == null || mapValue == null) {
			return;
		}
		Map<String, Object> map = (Map<String, Object>) req.getAttribute(attrKey);
		if (map == null) {
			map = new HashMap<String, Object>();
			req.setAttribute(attrKey, map);
		}
		map.put(mapKey, mapValue);
	}

	public static void del(String attrKey, String mapKey){
		HttpServletRequest req = getRequest();
		if (req == null || mapKey == null) {
			return;
		}
		Map<String, Object> map = (Map<String, Object>) req.getAttribute(attrKey);
		if (map == null) {
			return;
		}
		map.remove(mapKey);
	}

}
